import axios from 'axios'
import { ElMessage } from 'element-plus'  // 替换消息组件导入
import JSEncrypt from 'jsencrypt'  // 导入JSEncrypt库

const service = axios.create({
  baseURL: process.env.VITE_API_BASE_URL || 'http://localhost:8600',
  timeout: 5000,
  headers: {
    'Content-Type': 'application/json'
  }
})


// 请求拦截器
service.interceptors.request.use(
    config => {
      const token = localStorage.getItem('token')
      if (token) {
        config.headers.Authorization = `Bearer ${token}`
      }
      return config
    },
    error => {
      return Promise.reject(error)
    }
)

// 响应拦截器
service.interceptors.response.use(
    response => {
      return response.data
    },


    error => {
      // 获取错误信息
      const errorMessage = error.response?.data?.message ||
          error.message ||
          '请求异常，请检查网络'
      
      // 显示自动消失的提示信息
      ElMessage({
        message: errorMessage,
        type: 'error',
        duration: 3000,  // 3秒后自动关闭
        showClose: true  // 显示关闭按钮
      })

      // 401错误处理（未授权）
      if (error.response?.status === 401) {
        localStorage.removeItem('token')
        window.location.href = '/login'
      }
      
      // 返回一个已解决的Promise，防止错误继续传播到组件
      return Promise.resolve({
        code: error.response?.status || 500,
        message: errorMessage,
        success: false
      })
    }
)



// 加密函数
const encryptParams = (params, publicKey) => {
  if (!publicKey) return params;
  // 移除公钥最后6位
  const trimmedKey = publicKey.slice(0, -6);
  
  try {
    // 使用jsencrypt库加密数据
    const encrypt = new JSEncrypt();
    encrypt.setPublicKey(trimmedKey);
    const encryptedData = encrypt.encrypt(JSON.stringify(params));
    
    // 返回加密后的数据
    return {
      encryptedData: encryptedData
    };
  } catch (error) {
    console.error('加密失败:', error);
    return params;
  }
};

// 获取公钥并加密参数
const getPublicKeyAndEncrypt = async (params) => {
  try {
    const response = await service.get('/client-user/user/initSign');
    if (response.code === '200' && response.result && response.result.publicKey) {
      const publicKey = response.result.publicKey;
      console.log('获取到公钥:', publicKey);
      return encryptParams(params, publicKey);
    } else {
      console.error('获取公钥失败:', response);
      return params;
    }
  } catch (error) {
    console.error('获取公钥请求异常:', error);
    return params;
  }
};

// 加密GET请求
export const uget = async (url = '', params = {}, option = {}) => {
  if (!url) {
    return Promise.reject(`params 'url' not exist！`);
  }
  
  const encryptedParams = await getPublicKeyAndEncrypt(params);
  return service.get(url, {
    params: encryptedParams,
    ...option
  });
};

// 加密POST请求
export const upost = async (url = '', params = {}, option = {}) => {
  if (!url) {
    return Promise.reject(`params 'url' not exist！`);
  }
  
  const encryptedParams = await getPublicKeyAndEncrypt(params);
  return service.post(url, encryptedParams, option);
};

export default async (url = '', paramsInfo = {}, option = {}) => {
  if (!url) {
    return Promise.reject(`params 'url' not exist！`)
  }
  let params =  paramsInfo

  let method = option.method || 'post'
  switch (method) {
    case 'get':
      return service.get(url, {
        params: params
      })
    case 'post':
      return service.post(url, params, option)
    case 'put':
      return service.put(url, params, option)
    default:
      return Promise.reject(`unknown request method '${method}'`)
  }
}

